package cn.edu.csmzxy.rk233x.auth_system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysPermission;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysRolePermission;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysPermissionMapper;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysRolePermissionMapper;
import cn.edu.csmzxy.rk233x.auth_system.service.SysRolePermissionService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author wumxing
 * @date 2025/10/15 9:51
 * @description
 */

@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService {
    @Autowired
    private SysRolePermissionMapper rolePermissionMapper;
    @Autowired
    private SysPermissionMapper permissionMapper;
    @Override
    public List<SysPermission> getPermissionsByRoleId(Long roleId) {
        // 1. 查询角色-权限关联记录
        LambdaQueryWrapper<SysRolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRolePermission::getRoleId, roleId);
        List<SysRolePermission> rolePermissions = rolePermissionMapper.selectList(wrapper);
        if(rolePermissions.isEmpty()) return new ArrayList<SysPermission>();
        // 2. 提取权限ID并查询权限详情
        List<Long> permissionIds = rolePermissions.stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());
        return permissionMapper.selectBatchIds(permissionIds);
    }

    @Override
    @Transactional
    public void assignPermissions(Long roleId, List<Long> permissionIds) {
        // 先删除原有关联
        LambdaQueryWrapper<SysRolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRolePermission::getRoleId, roleId);
        rolePermissionMapper.delete(wrapper);

        // 新增关联
        for (Long permissionId : permissionIds) {
            SysRolePermission rolePermission = new SysRolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionMapper.insert(rolePermission);
        }
    }
}